function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//转换商品分类
function covertProductCates(productCates){
  if (productCates == undefined || productCates.length == 0) {
    return false;
  }

  for(var i = 0; i < productCates.length; i++){
    productCates[i].active = false;
  }

  return productCates;
}

function convertProducts(products){
  if (products == undefined || products.length == 0) {
    return false;
  }

  for(var i = 0; i < products.length; i++){
    products[i].price = parseFloat(products[i].price);
    products[i].num = 0;
    products[i].status = productStatus(products[i].status);
    for(var j = 0;j < products[i].specs.length;j++){
      products[i].specs[j].price = parseFloat(products[i].specs[j].price);
      products[i].specs[j].num = 0;
    }
  }

  return products;
}

function isCartProductExists(product, cartProducts){
  if(product == undefined || cartProducts == undefined){
    //TODO:是否合适
    return true;
  }

  if(cartProducts.length == 0){
    return -1;
  }

  for(var i = 0; i < cartProducts.length; i++){
    if(product.id == cartProducts[i].id){
      return i;
    }
  }

  return -1;
}

function productStatus(status){
  if(status == 1){
    return '已上架';
  }

  return '已下架';
}

function orderStatus(status){
  switch (parseInt(status)) {
    case 1:
      return '未支付';
    case 2:
      return '已支付';
    case 3:
      return '已取消';
    case 4:
      return '已发货';
    case 5:
      return '已收货';
    case 6:
      return '售后中';
    case 7:
      return '已完成';
    case 8:
      return '已退款';
    case 9:
      return '拒绝退款';
    case 10:
      return '同意退款';
    default:
      return '未知';
  }
}

function orderTime(time) {
  var create_time = new Date(time);
  var now = new Date();

  var interval = now.getTime() - create_time.getTime();
  if (interval < 3600000) {
    return parseInt(interval/60000)+'分钟前'
  } else if (interval < 86400000) {
    return parseInt(interval/3600000)+'小时前'
  } else {
    return time
  }
}

function login(app,cb){
  wx.login({
    success: function (res) {
      console.log(res);
      //授权登录，获取3rd_session
      app.func.req("index/wx_xcx_login", { code: res.code, app_id: app.app_id }, "GET", function (res) {
        console.log(res)
        var session_3rd = res.result.session_3rd;
        wx.getUserInfo({
          success: function (res) {
            app.userInfo = res.userInfo;
            //通过3rd_session换取openid / uniqueID / token，在服务端完成
            //返回成功后获取到token
            app.func.req("index/xcx_user_update", {
              session_3rd: session_3rd,
              rawData: res.rawData,
              signature: res.signature,
              encryptedData: res.encryptedData,
              iv: res.iv
            }, "POST", function (res) {
              var token = res.result;
              try {
                wx.setStorageSync('token', token);
              } catch (e) {
                console.log(e)
              }
              return typeof cb == "function" && cb(true)
            });
          },
          fail: function(){
            console.log('调用失败')
            wx.showModal({
              title: '提示',
              content: '需要获取你的授权才能正常使用。请在设置页面允许使用你的“用户信息”。',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: (res) => {
                      if(res.authSetting['scope.userInfo']){
                      wx.getUserInfo({
                        success: function(res){
                          app.func.req("index/xcx_user_update", {
                            session_3rd: session_3rd,
                            rawData: res.rawData,
                            signature: res.signature,
                            encryptedData: res.encryptedData,
                            iv: res.iv
                          }, "POST", function (res) {
                            var token = res.result;
                            try {
                              wx.setStorageSync('token', token);
                            } catch (e) {
                              console.log(e)
                            }
                            return typeof cb == "function" && cb(true)
                          });
                        }
                      });
                      }else{
                        return login(app, cb)
                      }
                    }
                  })
                }
              }
            })
          }
        });
      });
    },
    fail: function () {
      wx.login();
    }
  });
}

function newLogin(app,cb){
  wx.login({
    success: function (res) {
      console.log(res);
        wx.getUserInfo({
            success:function(info){
              console.log('info success');
                var nickname = info.userInfo.nickName;
                var avatar = info.userInfo.avatarUrl;

      //授权登录，获取3rd_session
      app.func.req("index/wx_xcx_login", { code: res.code, app_id: app.app_id ,nickname:nickname,avatar:avatar}, "GET", function (res) {
        console.log(res)
        var session_3rd = res.result.session_3rd;
        var token = res.result.token;

        try {
          wx.setStorageSync('token', token);
          wx.setStorageSync('session_3rd', session_3rd);
        } catch (e) {
          console.log(e)
        }

        return typeof cb == "function" && cb(true)
      });
        },
      fail: function (e) {
        return typeof cb == "function" && cb('error');
        console.log('info error');
        wx.login();
      }
        });
    },
    fail: function () {
      wx.login();
    }
  });
}

function userAuth(app, res, cb){
  if (!app || !res || !cb) {
    return false;
  }

  app.func.req("index/xcx_user_update", {
    session_3rd: wx.getStorageSync('session_3rd'),
    rawData: res.rawData,
    signature: res.signature,
    encryptedData: res.encryptedData,
    iv: res.iv
  }, "POST", function (res) {
    return typeof cb == "function" && cb(true)
  });
}

function appInfo(app, cb){
  app.func.req("index/app_info", {
    app_id: app.app_id,
  }, "GET", function (res) {

    return typeof cb == "function" && cb(res)
  });
}

module.exports = {
  formatTime: formatTime,
  covertProductCates: covertProductCates,
  convertProducts: convertProducts,
  isCartProductExists: isCartProductExists,
  productStatus: productStatus,
  orderStatus: orderStatus,
  orderTime: orderTime,
  login: login,
  newLogin: newLogin,
  userAuth: userAuth,
  appInfo: appInfo
}
